#include "ollamaClientPlugin.h"
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QtConcurrent/QtConcurrentRun>
#include <QApplication>
#include <QJsonDocument>
#include <QJsonObject>

ollamaClientPlugin::ollamaClientPlugin()
{
}

QString ollamaClientPlugin::createPluginMenu()
{
	return "ai/ollama";
}

void ollamaClientPlugin::createPluginMenuResult(bool result, QString menuId, QString error)
{
	// TODO
}

QWidget* ollamaClientPlugin::createPluginWidget()
{
	if (m_widget == nullptr)
	{
		m_widget = new ollamaClientWidget;
	}
	return m_widget;
}

void ollamaClientPlugin::destroyPluginWidget()
{
	if (m_widget)
	{
		delete m_widget;
		m_widget = nullptr;
	}
}


#include <QVboxLayout>
#include <QTextEdit>
#include <QLineEdit>
#include <QToolButton>
ollamaClientWidget::ollamaClientWidget(QWidget* parent)
    :QWidget(parent)
{
    QVBoxLayout* mainlayout = new QVBoxLayout(this);

    QTextEdit* textEdit = new QTextEdit;
    mainlayout->addWidget(textEdit, 1);
    QLineEdit *lineEdit = new QLineEdit;
    QHBoxLayout *lineEditLayout = new QHBoxLayout;
    m_btnSend = new QToolButton;
    m_btnSend->setText("Send");
    lineEditLayout->addWidget(lineEdit);
    lineEditLayout->addWidget(m_btnSend);
    mainlayout->addLayout(lineEditLayout);

    connect(m_btnSend, &QToolButton::clicked, [this, lineEdit]() {
        static bool staticRunning = false;
        if (staticRunning)
            return;
        staticRunning = true;
        QString text = lineEdit->text();
        emit this->sigAppendResponse(tr("ask: ") + text);
        emit this->sigAppendResponse(tr("wait........"));
        QtConcurrent::run([this, text]() {
            QNetworkAccessManager networkAccessManager;
            const QUrl url = QUrl::fromUserInput("http://localhost:11434/api/generate");
            QNetworkRequest req(url);
            req.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
            QJsonObject jsParams;
            jsParams.insert("model", "deepseek-r1:7b");
            jsParams.insert("prompt", text);
            jsParams.insert("stream", false);
            QNetworkReply* reply = networkAccessManager.post(req, QJsonDocument(jsParams).toJson());
            while (!reply->isFinished())
            {
                if (qApp->closingDown())
                    return;
                QCoreApplication::processEvents();
                QThread::msleep(10);
            }
            QByteArray replyData = reply->readAll();
            reply->deleteLater();
            QJsonDocument jsDoc = QJsonDocument::fromJson(replyData);
            QJsonObject jsReply = jsDoc.object();
            QString response = jsReply.value("response").toString();
            emit this->sigAppendResponse(response);
            staticRunning = false;
        });
    });

    connect(this, &ollamaClientWidget::sigAppendResponse, [=](const QString& response) {
        QTextEdit* textEdit = qobject_cast<QTextEdit*>(this->findChild<QTextEdit*>());
        textEdit->append(response);
        });
}

void ollamaClientWidget::keyPressEvent(QKeyEvent* event)
{
    m_btnSend->click();
    QWidget::keyPressEvent(event);
}